<?php

class Application_Model_VoitureDAO
{
	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if(is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if(!$dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
 
	public function getDbTable()
	{
		if(null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Voiture');
		}
		return $this->_dbTable;
	}
	
	public function save(Default_Model_Voiture $voiture)
	{
		$data = array(
			'VOINUM' => $voiture->getVoiNum(),
			'ECUNUM' => $voiture->getEcuNum(),
			'TYPNUM' => $voiture->getType()->getTypNum(),
			'VOINOM' => $voiture->getVoiNom(),
			'VOIADRESSEIMAGE' => $voiture->getVoiAdresseImage()
		);
 
		if (null === ($voiNum = $voiture->getVoiNum()))
		{
			unset($data['PAYNUM']);
			$this->getDbTable()->insert($data);
        }
        else
        {
			$this->getDbTable()->update($data, array('VOINUM = ?' => $voiNum));
		}
	}
	
	public function find($voiNum)
	{
		$voiture = new Application_Model_Voiture();

		$result = $this->getDbTable()->find($voiNum);
		if(0 == count($result))
		{
			return null;
		}
		$row = $result->current();
		$voiture->setVoiNum($row->VOINUM)
			 ->setEcuNum($row->ECUNUM)
			 ->setVoiNom($row->VOINOM)
			 ->setVoiAdresseImage($row->VOIADRESSEIMAGE);
		
		//On recupere le type
		$typeVoitureDAO = new Application_Model_TypeVoitureDAO();
		$type = $typeVoitureDAO->find($row->TYPNUM);
		$voiture->setType($type);
		
		return $voiture;
	}
	
	public function findAll()
	{
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->from('voiture',array('VOINUM'))->order('TYPNUM ASC'));
		$entries = array();
		foreach($resultSet as $row)
		{
			$entries[] = $this->find((int)$row->VOINUM);
		}
		return $entries;
	}
	
	public function findByEcurie($ecuNum)
	{
		$resultSet = $this->getDbTable()->fetchAll($this->getDbTable()->select()->from('voiture',array('VOINUM'))->where('ECUNUM = '.$ecuNum)->order('TYPNUM ASC')->order('VOINOM ASC'));
		$entries = array();
		foreach($resultSet as $row)
		{
			$entries[] = $this->find((int)$row->VOINUM);
		}
		return $entries;
	}
}